package com.jnu.bookstore;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.jnu.bookstore.data.Book;
import com.jnu.bookstore.data.DataBank;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BookListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BookListFragment extends Fragment {
    private List<Book> shopItems;
    public static final int RESULT_CODE_ADD_DATA = 996;
    private MyBookstoreAdapter recyclerViewAdapter;
    public static final int REQUEST_CODE_ADD = 123;
    public static final int REQUEST_CODE_EDIT = 124;
    private DataBank dataBank;


    public BookListFragment() {
        // Required empty public constructor
    }


    public static BookListFragment newInstance() {
        BookListFragment fragment = new BookListFragment();
        Bundle args = new Bundle();

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {

        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View roootView=inflater.inflate(R.layout.fragment_book_list, container, false);
        initData();
        RecyclerView mainRecycleView = roootView.findViewById(R.id.recycle_view_books);
        LinearLayoutManager layoutManager=new LinearLayoutManager(this.getContext());
        mainRecycleView.setLayoutManager(layoutManager);//设置布局管理器

        //设置Adapter
        recyclerViewAdapter=new MyBookstoreAdapter(shopItems);
        mainRecycleView.setAdapter(recyclerViewAdapter);

        return roootView;
    }


    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_ADD) {
            if (resultCode == RESULT_CODE_ADD_DATA) {
                String name = data.getStringExtra("name");
                int position=data.getIntExtra("position",shopItems.size());
                shopItems.add(position,new Book(name, R.drawable.book_no_name));
                dataBank.saveData();
                recyclerViewAdapter.notifyItemInserted(position);
            }
        }
        if (requestCode == REQUEST_CODE_EDIT) {
            if (resultCode == RESULT_CODE_ADD_DATA) {
                String name = data.getStringExtra("name");
                int position=data.getIntExtra("position",shopItems.size());
                shopItems.get(position).setName(name);
                shopItems.get(position).setPictureID(R.drawable.book_no_name);
                dataBank.saveData();
                recyclerViewAdapter.notifyItemChanged(position);
            }
        }
    }

  public void initData() {
      shopItems=new ArrayList<>();
      dataBank=new DataBank(this.getContext());
      /*shopItems= dataBank.loadData();*/
      shopItems.add(new Book("软件项目管理案例教程（第4版）",R.drawable.book_2));
      shopItems.add(new Book("创新工程实践", R.drawable.book_no_name));
      shopItems.add(new Book("信息安全数学基础（第2版）", R.drawable.book_1));
    }

    private class MyBookstoreAdapter extends RecyclerView.Adapter {
        private List<Book> shopItems;

        public MyBookstoreAdapter(List<Book> shopItems) {
            this.shopItems=shopItems;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.recycle_view_books, parent, false);
            return new BookListFragment.MyBookstoreAdapter.MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull  RecyclerView.ViewHolder Holder, int position) {
            BookListFragment.MyBookstoreAdapter.MyViewHolder myholder= (BookListFragment.MyBookstoreAdapter.MyViewHolder)Holder;

            myholder.getImageView().setImageResource(shopItems.get(position).getCoverResourceId());
            myholder.getTextViewName().setText(shopItems.get(position).getTitle());
        }

        @Override
        public int getItemCount() {
            return shopItems.size();
        }

        private class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
            private final ImageView imageView;
            private final TextView textViewName;

            public MyViewHolder(View itemview) {
                super(itemview);
                this.imageView=itemview.findViewById(R.id.image_view_book_cover);
                this.textViewName=itemview.findViewById(R.id.text_view_book_title);
                itemview.setOnCreateContextMenuListener(this);

            }
            public ImageView getImageView() {
                return imageView;
            }

            public TextView getTextViewName() {
                return textViewName;
            }

            public List<Book> getListBooks() {
                return shopItems;
            }

            @Override
            public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
                int position=getAdapterPosition();
                MenuItem delete=contextMenu.add(Menu.NONE,1,1,"删除");
                MenuItem add=contextMenu.add(Menu.NONE,2,2,"添加");
                MenuItem edit=contextMenu.add(Menu.NONE,3,3,"修改");
                delete.setOnMenuItemClickListener((MenuItem.OnMenuItemClickListener)this);
                add.setOnMenuItemClickListener((MenuItem.OnMenuItemClickListener)this);
                edit.setOnMenuItemClickListener((MenuItem.OnMenuItemClickListener)this);
            }

            public boolean onMenuItemClick(MenuItem menuItem){
                final int posistion=getAdapterPosition();
                Intent intent;
                switch (menuItem.getItemId()) {
                    case 1:
                        AlertDialog.Builder alertDB = new AlertDialog.Builder(BookListFragment.this.getContext());
                        alertDB.setPositiveButton(BookListFragment.this.getContext().getResources().getString(R.string.string_confirmation), (dialogInterface, i) -> {
                            shopItems.remove(posistion);
                            dataBank.saveData();
                            BookListFragment.MyBookstoreAdapter.this.notifyItemRemoved(posistion);
                        });
                        alertDB.setNegativeButton(BookListFragment.this.getContext().getResources().getString(R.string.string_cancel), (dialogInterface, i) -> {

                        });
                        alertDB.setMessage(BookListFragment.this.getContext().getResources().getString(R.string.string_confirm_delete) +shopItems.get(posistion).getName()+"？");
                        alertDB.setTitle(BookListFragment.this.getContext().getResources().getString(R.string.hint)).show();
                        break;

                    case 2:
                        /*final View dialagueView= LayoutInflater.from(MainActivity.this).inflate(R.layout.dialogue_input_item,null);
                        AlertDialog.Builder alertDialogBuiler = new AlertDialog.Builder(MainActivity.this);
                        alertDialoBuiler.setView(dialagueView);

                        alertDialogBuiler.setPositiveButton("确定",new DialogInterface.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                EditText editName=dialagueView.findViewById(R.id.edit_text_name);
                                shopItems.add(posistion,new Book(editName.getText().toString(),R.drawable.book_1));
                                MyBookstoreAdapter.this.notifyItemInserted(position);
                            }
                        });
                        alertDialogBuiler.setCancelable(false).setNegativeButton ("取消",new DialogInterface.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        });
                        alertDialogBuiler.create().show();;
                        final View dialogueView=LayoutInflater.from(MainActivity.this).inflate(R.layout.dialogue_input_item,null);
                        final AlertDialog.Builder alterDialogBuilder=new AlertDialog.Builder(MainActivity.this);
                        alterDialogBuilder.setView(dialogueView);
                        alterDialogBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                EditText editName= dialogueView.findViewById(R.id.edit_text_name);
                                shopItems.add(posistion,new Book(editName.getText().toString(),R.drawable.book_1));
                                MyBookstoreAdapter.this.notifyItemInserted(posistion);
                            }
                        });
                        alterDialogBuilder.setCancelable(false).setNegativeButton("取消", new DialogInterface.OnClickListener(){//点否
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {


                            }
                        });
                        alterDialogBuilder.create().show();*/
                        intent=new Intent(BookListFragment.this.getContext(), EditbookActivity.class);
                        intent.putExtra("position",posistion);
                        BookListFragment.this.startActivityForResult(intent, REQUEST_CODE_ADD);
                        break;
                    case 3:
                        /*shopItems.get(position).setName("测试修改");
                        MyBookstoreAdapter.this.notifyItemChanged(position);*/
                        intent=new Intent(BookListFragment.this.getContext(), EditbookActivity.class);
                        intent.putExtra("position",posistion);
                        intent.putExtra("name",shopItems.get(posistion).getName());
                        BookListFragment.this.startActivityForResult(intent, REQUEST_CODE_EDIT);

                        break;
                }

                return false;
            }


        }
    }
}